//
//  NetWorkHandle.m
//  NetWork
//
//  Created by lanou3g on 15/11/5.
//  Copyright © 2015年 照日格图. All rights reserved.
//

#import "NetWorkHandle.h"

@implementation NetWorkHandle

+ (void)getDataWithURLString:(NSString *)string
                     compare:(NetBlock)block
{
    
    // 对地址做一次UTF－8的转码，防止参数里面有中文
    NSString *urlString = [string stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    
    NSURL *url = [NSURL URLWithString:urlString];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    // 初始化一个NSURLSession
    NSURLSession *session = [NSURLSession sharedSession];
    [[session downloadTaskWithRequest:request completionHandler:^(NSURL * _Nullable location, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        
        
        
        // 在主队列干活儿
        dispatch_async(dispatch_get_main_queue(), ^{
            
            NSData *data = [NSData dataWithContentsOfURL:location];
            if (data == nil || error) {
                NSLog(@"网络解析出错了");
                return;
            }
            id object = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
            block(object);
        });
        
        // resume 因为任务默认是挂起状态，需要恢复任务
    }]resume];
    
}

+ (void)postDataWithURLString:(NSString *)string
                andBodyString:(NSString *)bodyString
                      compare:(NetBlock)block
{
    NSString *urlString = [string stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    
    NSURL *url = [NSURL URLWithString:urlString];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    
    NSData *data = [bodyString dataUsingEncoding:NSUTF8StringEncoding];
    
    [request setHTTPMethod:@"POST"];
    [request setHTTPBody:data];
    
    // 初始化一个NSURLSession
    NSURLSession *session = [NSURLSession sharedSession];
    [[session downloadTaskWithRequest:request completionHandler:^(NSURL * _Nullable location, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        
        // 在主队列干活儿
        dispatch_async(dispatch_get_main_queue(), ^{
            
            NSData *data = [NSData dataWithContentsOfURL:location];
            id object = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
            block(object);
            
        });
        // resume 因为任务默认是挂起状态，需要恢复任务
    }]resume];
}

@end
